﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.Collections.ObjectModel;
using BrainTechLLC.ImageOperators;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using BrainTechLLC;
using CPPClassLibrary;
using DirectoryViewModels;
using ImageAppDataModels;
using ImageAppViewModels;
using System.IO;
using System.Collections.Generic;
using System.Text;
using BrainTechLLC.ThreadSafeObjects;
using System.Drawing;
using System.Windows.Media;
using System.Reflection;
using BinaryNorthwest;
using BrainTechLLC.FilterExtensions;


namespace WpfImageDuplicates
{
    public partial class Window1
    {
        public bool _suspendDirsViewModelCollectionChanged;

        void imageCollectionView_WantView(object sender, ObjectEventArgs<FileImageViewModel> e)
        {
            FileImageCollectionViewModels[0]._currentIndex = -1;
            _FullViewerHandler.Handler.OpenWindow(e.obj);
        }

        void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Console.WriteLine(e.Exception.ToString());
        }

        void Values_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "DirectoriesVisible")
            {
                FileImageCollectionViewModels.ForEach(o => ShowOrHideDirectories(o.DirectoriesVisible));
            }
            else if (e.PropertyName == "ThumbnailsVisible")
            {
                FileImageCollectionViewModels.ForEach(o => ShowOrHideThumbnails(o.ThumbnailsVisible));
            }
            else if (e.PropertyName == "FolderExplorerVisible")
            {
                FileImageCollectionViewModels.ForEach(o => ShowOrHideFolderExplorer(o.FolderExplorerVisible));
            }
            else if (e.PropertyName == "FilterExplorerVisible")
            {
                FileImageCollectionViewModels.ForEach(o => ShowOrHideMultipleHandler(o.FilterExplorerVisible));
            }
            else if (e.PropertyName == "FullViewerVisible")
            {
                FileImageCollectionViewModels.ForEach(o => ShowOrHideFullViewer(o.FullViewerVisible));
            }
            else if (e.PropertyName == "ShowCommandBar")
            {
                ShowOrHideCommandBar(SettingsWatcher.SettingsViewModelDynamic.ShowCommandBar);
            }
            else if (e.PropertyName == "ShowFilters")
            {
                if (!SettingsWatcher.SettingsViewModelDynamic.ShowFilters)
                {
                    Settings.Values.FilterExplorerVisible = false;
                }                
                ShowOrShowFilters(SettingsWatcher.SettingsViewModelDynamic.ShowFilters);
            }
            else if (e.PropertyName == "FolderListVisible")
            {
                ShowOrHideDirectoryOrganizer(SettingsWatcher.SettingsViewModelDynamic.FolderListVisible);
            }
            else if (e.PropertyName == "GroupOrganizerVisible")
            {
                ShowOrHideGroupOrganizer(SettingsWatcher.SettingsViewModelDynamic.GroupOrganizerVisible);
            }
            else if (e.PropertyName == "FolderExplorerTopmost")
            {
                if (_FolderHandler.IsLoaded)
                {
                    _FolderHandler.Handler.AlwaysOnTop = SettingsWatcher.SettingsViewModelDynamic.FolderExplorerTopmost;
                }
            }
        }

        private void WantBlur(object sender, ExecutedRoutedEventArgs e)
        {
            CollectionViews.ForEach(o => Commands.WantBlurCommand.Execute(o.BlurHandler));
        }

        private void WantCompareMultiple(object sender, ExecutedRoutedEventArgs e)
        {
            CollectionViews.ForEach(o => Commands.WantCompareMultipleCommand.Execute(_CompareMultiple.Handler, o.GetSelectedImages()));
        }

        private void WantCompareMultipleInNewWindow(object sender, ExecutedRoutedEventArgs e)
        {
            ObservableCollection<FileImageViewModel> toCompare = e.Parameter as ObservableCollection<FileImageViewModel>;
            _CompareMultiple.Handler.OpenAskWindow(toCompare, string.Empty);
        }

        private void WantRefreshThumbs(object sender, ExecutedRoutedEventArgs e)
        {
            foreach (var collectionVm in FileImageCollectionViewModels)
            {
                CollectionViews.ForEach(o => Commands.WantRefreshThumbsCommand.Execute(collectionVm, o.GetAllThumbnailViews()));
            }
        }

        private void ViewSettings(object sender, ExecutedRoutedEventArgs e)
        {
            Commands.ViewSettingsCommand.Execute(_SettingsHandler.Handler, this);
        }

        private void WantViewFullCommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            Type t = e.Parameter.GetType();

            if (t == typeof(FileImageViewModel))
            {
                FileImageCollectionViewModels[0]._currentIndex = -1;
                _FullViewerHandler.Handler.OpenWindow(e.Parameter as FileImageViewModel);
            }
            else if (t == typeof(string))
            {
                string fileName = e.Parameter as string;

                if (!string.IsNullOrEmpty(fileName))
                {
                    var vm = FileImageCollectionViewModels.Find(fileName);

                    if (vm != null)
                    {
                        FileImageCollectionViewModels[0]._currentIndex = -1;
                        _FullViewerHandler.Handler.OpenWindow(vm);
                    }
                }
            }
        }

        private void ViewStats(object sender, ExecutedRoutedEventArgs e)
        {
            Commands.ViewStatsCommand.Execute(_StatsHandler.Handler, this);
        }

        private void RemoveDuplicates(object sender, ExecutedRoutedEventArgs e)
        {            
            _CompareHandler.Handler.OpenWindow(this);
        }

        private void ViewFolderExplorer(object sender, ExecutedRoutedEventArgs e)
        {
            Commands.ViewFolderExplorerCommand.Execute(_FolderHandler.Handler, this);
        }

        private void ShowMultipleImagesCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            Commands.ShowMultipleImagesCommand.Execute(_ShowMultipleHandler.Handler, this);
        }

        void _dirsViewModel_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (!_suspendDirsViewModelCollectionChanged)
            {
                RefreshDirsViewModel();
            }
        }

        private static void RefreshDirsViewModel()
        {
            Console.WriteLine("Refreshing Directory View Models");
            try
            {
                Window1.MainWindow.CollectionViews = null;

                Window1.MainWindow._AllFileImageCollectionViewModels.ForEach(o => o._fileImageCollection.ClearAllItems());
                Window1.MainWindow.ClearFileImageCollections();
                Window1.MainWindow._FileImageCollectionViewModels = null;
                _doNotStartFileImageCollectionDirectoryReader = false;

                for (int n = 0; n < Window1.MainWindow.CollectionViews.Count; n++)
                {
                    var collectionView = Window1.MainWindow.CollectionViews[n];
                    var fileImages = Window1.MainWindow.FileImageCollectionViewModels[n];

                    collectionView.FileImageCollectionViewModel = fileImages;
                    collectionView._HasSorted = true;
                }

                Settings.Values.OrderedFileNames.Clear();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        protected void WantView(object sender, ObjectEventArgs<FileImageViewModel> args)
        {
            FileImageCollectionViewModels[0]._currentIndex = -1;
            _FullViewerHandler.Handler.OpenWindow(args.obj);
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (_FullViewerHandler.IsLoaded)
            {
                _FullViewerHandler.Handler.Close();
            }
            HandleCleanupAndSave();
        }

        private void collectionView_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            CollectionViews.ForEach(o => o.ForceRefresh = true);
        }

        private void ChangeThumbnailSize(object sender, ObjectEventArgsNonRef<double, double> e)
        {
            SettingsWatcher._settings.ThumbWidth = e.obj1;
            SettingsWatcher._settings.ThumbHeight = e.obj2;
            FileImageCollectionViewModels.ForEach(o => o.InvalidateAllThumbnails(false));
            CollectionViews.ForEach(o => o.ForceRefresh = true);
            CollectionViews.ForEach(o => o.GetAllThumbnailViews().ForEach((thumb) => thumb.SetFileNamePosition()));
        }

        private void ViewFullImage(object sender, EventArgs e)
        {
            FileImageCollectionViewModels[0]._currentIndex = -1;
            _FullViewerHandler.Handler.ViewFullImage();
        }

        private void SaveSettings(object sender, ExecutedRoutedEventArgs e)
        {
            Commands.SaveSettingsCommand.Execute(SettingsWatcher);
        }

        private void Extra1CommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            Commands.Extra1Command.Execute(FileImageCollectionViewModels);
        }

        private void mnuExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void splitter1_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            SettingsWatcher.SettingsViewModelDynamic.MainGridRow1Height = mainGrid.RowDefinitions[1].ActualHeight;
            CollectionViews[0].Visibility = System.Windows.Visibility.Visible;
        }

        private void btnClose_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            SettingsWatcher.SettingsViewModelDynamic.ShowFilters = false;
            ShowOrShowFilters(SettingsWatcher.SettingsViewModelDynamic.ShowFilters);
        }

        private void mnuDeleteThumbnailCache_Click(object sender, RoutedEventArgs e)
        {
            CurrentDirectoriesToExamine.DeleteThumbnailCache();
        }

        private void mnuTest_Click(object sender, RoutedEventArgs e)
        {
            string objList = CountObjects().ToString();
            MessageBox.Show(string.Format("Thumbnails: {0}", ThumbViewBottom.wiredUp.Count) + Environment.NewLine + objList);
        }

        //private void mnuFilters_Checked(object sender, RoutedEventArgs e)
        //{
        //    FileImageCollectionViewModels.ForEach(o => o.FilterExplorerVisible = true);
        //    ShowOrHideFilterExplorer(true);
        //    Settings.Values.FilterExplorerVisible = true;
        //    Settings.Values.ShowFilters = false;
        //}

        //private void mnuFilters_Unchecked(object sender, RoutedEventArgs e)
        //{
        //    Settings.Values.FilterExplorerVisible = false;
        //    Settings.Values.ShowFilters = true;
        //}

        private void Window_Activated(object sender, EventArgs e)
        {
            if (_CollectionViews != null)
            {
                CollectionViews.ForEach(o => o.HighlightLastSelected());
            }
        }

        void FullViewerHandler_RequestRotate(object sender, ObjectEventArgsNonRef<RotationParams, bool> e)
        {
            var rotationParams = e.obj1;
            RotateViewModel(rotationParams);
        }

        void FullViewerHandler_RequestResizeDelete(object sender, ObjectEventArgsNonRef<FileImageViewModel, bool> e)
        {
            var vm = e.obj1;
            var singleDelete = e.obj2;
            ResizeDeleteViewModel(vm, singleDelete);
        }

        void FullViewerHandler_RequestResize(object sender, ObjectEventArgsNonRef<FileImageViewModel, bool> e)
        {
            var vm = e.obj1;
            var singleDelete = e.obj2;
            ResizeViewModel(vm, singleDelete);
        }

        private void mnuSaveFilters_Click(object sender, RoutedEventArgs e)
        {
            if (FilterHandler != null)
            {
                FilterHandler.SaveData();
            }
        }

        private void mnuSaveSettings_Click(object sender, RoutedEventArgs e)
        {
            SettingsWatcher.SettingsViewModel.ReadSettings(this);
            DirectoriesCollectionsToExamine.Save(FilePaths._pathToExaminePath);
            SettingsWatcher.SaveData();
        }
    }
}
